﻿using Bootstrap.Security;
using Longbow.Cache;
using Longbow.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Bootstrap.DataAccess.Model;
using Longbow.Web.Mvc;
using PetaPoco;
using System.Net;
using System.Text;
using Longbow.Configuration;

namespace Bootstrap.DataAccess
{
    /// <summary>
    /// 活动呼叫
    /// </summary>
    public static class ActiveCallsHelper
    {
        public const string RetrieveActiveCallsDataKey = "UserHelper-RetrieveActiveCalls";
        public const string RetrieveActiveCallsByRoleIdDataKey = "UserHelper-RetrieveActiveCallsByRoleId";
        public const string RetrieveActiveCallsByGroupIdDataKey = "UserHelper-RetrieveActiveCallsByGroupId";
        public const string RetrieveNewActiveCallsDataKey = "UserHelper-RetrieveNewActiveCalls";
        public const string RetrieveActiveCallsByNameDataKey = "BootstrapUser-RetrieveActiveCallsByName";

        /// <summary>
        /// 查询活动呼叫
        /// </summary>
        /// <returns></returns>
        public static Page<ActiveCalls> RetrievePages(PaginationOption op) =>
            DbContextManager.Create<ActiveCalls>().RetrievePages(op);





        /// <summary>
        ///  拆线or代接
        /// </summary>
        /// <returns></returns>
        public static bool SendAction(ActiveCalls ActiveCalls)
        {
            try
            {
                string _result = string.Empty, msg = string.Empty;

                //msg：转入座席： ActionForceTrans | callid | ExtNo
                //拆线： ActionForceDisconnect | callid（多个callID以英文逗号隔开）
                if (!string.IsNullOrEmpty(ActiveCalls.uuid) && !string.IsNullOrEmpty(ActiveCalls.dest)) //转入座席
                {
                    msg = "ActionForceTrans|" + ActiveCalls.uuid + "|" + ActiveCalls.dest;
                }
                //按uuid 拆线   uuid不为空、分机号为空时
                else if (ActiveCalls.uuid != "#" && !string.IsNullOrEmpty(ActiveCalls.uuid) && string.IsNullOrEmpty(ActiveCalls.dest))
                {
                    msg = "ActionForceDisconnect|" + ActiveCalls.uuid;
                }
                else if (ActiveCalls.uuid == "#")//全部拆线 
                {
                    msg = "ActionForceDisconnectAll|";
                }

                PostSend(ConfigurationManager.AppSettings["SendUrl"], "/" + msg, out _result);

                return true;

            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 最大呼入量呼出量
        /// </summary>
        public static void CallNum(ActiveCalls active)
        {
            try
            {
                var db = DbManager.Create();
                //获取当天呼入量呼出量数据
                var num = DbManager.Create().Fetch<callnum>("select * from callnum where Date like '%" + DateTime.Now.ToString("yyyy-MM-dd") + "%'");
                if (num.Count > 0)//有当天数据
                {
                    //呼入量不为空，并大于DB中当前呼入量
                    if (!string.IsNullOrEmpty(active.InCall) && int.Parse(active.InCall) > int.Parse(num[0].vCallNum))
                    {
                        //更新最大呼入量
                        db.Execute("update callnum set Date=@0,vCallNum=@1 where Date like '%" + DateTime.Now.ToString("yyyy-MM-dd") + "%'",
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), active.InCall);
                    }
                    //呼出量不为空，并大于DB中当前呼出量
                    if (!string.IsNullOrEmpty(active.OutCall) && int.Parse(active.OutCall) > int.Parse(num[0].vOutCallNum))
                    {
                        //更新最大呼出量
                        db.Execute("update callnum set OutDate=@0,vOutCallNum=@1 where OutDate like '%" + DateTime.Now.ToString("yyyy-MM-dd") + "%'",
                                   DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), active.OutCall);
                    }
                }
                else//无当天数据
                {
                    //插入当天数据
                    db.Execute("insert into callnum(Date,vCallNum,OutDate,vOutCallNum) values(@0,@1,@2,@3)",
                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), active.InCall, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), active.OutCall);
                }
            }
            catch { }


        }


        /// <summary>
        /// 调用wcf
        /// </summary>
        /// <param name="postUrl"></param>
        /// <param name="postData"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static bool PostSend(string postUrl, string postData, out string result)
        {
            try
            {

                string contentType = "application/x-www-form-urlencoded";
                //byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl + postData);
                httpWebRequest.Method = "get";
                httpWebRequest.ContentType = contentType;
                //httpWebRequest.ContentLength = byteArray.Length;

                httpWebRequest.Timeout = 2000;

                using (HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse)
                {

                    System.IO.Stream responseStream = httpWebResponse.GetResponseStream();

                    System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                    result = streamReader.ReadToEnd(); //请求返回的数据
                    result = result.Replace("\\", "").TrimStart('"').TrimEnd('"');
                    httpWebResponse.Close();
                    streamReader.Close();
                    streamReader.Dispose();


                }

                return true;
            }

            catch (Exception ex)
            {
                result = ex.Message;
                return false;
            }
        }



    }
}
